﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="App.xaml.cs" company="Mar3ek">
//   This code is licensed under the Mozilla Public License 2.0.
//   You can find the full license text at the following address:
//   https://winkee.codeplex.com/license
// </copyright>
// <summary>
//   Provides application-specific behavior to supplement the default Application class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace WinKee
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;

    using Windows.ApplicationModel;
    using Windows.ApplicationModel.Activation;
    using Windows.ApplicationModel.Email;
    using Windows.Phone.UI.Input;
    using Windows.Storage;
    using Windows.UI.Popups;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;

    using WinKee.Common;
    using WinKee.Dialogs;
    using WinKee.Models;
    using WinKee.Pages;

    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    public sealed partial class App
    {
        #region Fields

        /// <summary>
        /// The semaphore used to enforce OnFileActivated, OnResuming execution order.
        /// </summary>
        private static readonly Semaphore Semaphore = new Semaphore(1, 1);

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="App"/> class. 
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += this.OnSuspending;
            this.Resuming += this.OnResuming;
            this.UnhandledException += this.App_OnUnhandledException;
            this.ContinuationManager = new ContinuationManager();
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets the root frame.
        /// </summary>
        public static Frame RootFrame { get; private set; }

        /// <summary>
        /// Gets the continuation manager.
        /// </summary>
        public ContinuationManager ContinuationManager { get; private set; }

        #endregion

        #region Methods

        /// <summary>
        /// Handles the Activated event
        /// </summary>
        /// <param name="e">
        /// The event arguments.
        /// </param>
        protected override async void OnActivated(IActivatedEventArgs e)
        {
            Debug.WriteLine("OnActivated: " + e.PreviousExecutionState);

            this.CreateRootFrame();

            // Restore the saved session state only when appropriate
            if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                try
                {
                    await SuspensionManager.RestoreAsync();
                }
                catch (SuspensionManagerException)
                {
                    // Something went wrong restoring state.
                    // Assume there is no state and continue
                }
            }

            // Check if this is a continuation
            var continuationEventArgs = e as IContinuationActivatedEventArgs;
            if (continuationEventArgs != null)
            {
                this.ContinuationManager.Continue(continuationEventArgs);
            }

            Window.Current.Activate();
        }

        /// <summary>
        /// Handles the FileActivated event.
        /// </summary>
        /// <param name="e">
        /// The event arguments.
        /// </param>
        protected override void OnFileActivated(FileActivatedEventArgs e)
        {
            Semaphore.WaitOne();
            try
            {
                if (e.Files.Count <= 0)
                {
                    return;
                }

                this.CreateRootFrame();

                var file = e.Files[0] as StorageFile;
                if (file == null)
                {
                    return;
                }
                
                using (var content = file.OpenAsync(FileAccessMode.Read).AsTask().Result)
                using (var ms = new MemoryStream())
                {
                    content.GetInputStreamAt(0).AsStreamForRead().CopyTo(ms);
                    var stringContent = Convert.ToBase64String(ms.ToArray());
                    RootFrame.Navigate(typeof(MainPage), file.Name + "|" + stringContent);
                    Window.Current.Activate();
                }
            }
            finally
            {
                Semaphore.Release();
            }
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="e">
        /// Details about the launch request and process.
        /// </param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }

#endif
            this.CreateRootFrame();

            if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                // Restore the saved session state only when appropriate
                try
                {
                    await SuspensionManager.RestoreAsync();
                }
                catch (SuspensionManagerException)
                {
                    // Something went wrong restoring state.
                    // Assume there is no state and continue
                }
            }

            if (RootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                RootFrame.Navigate(typeof(MainPage), e.Arguments);
            }

            SuspensionManager.KnownTypes.Add(typeof(PasswordEntry));
            SuspensionManager.KnownTypes.Add(typeof(List<PasswordEntry>));

            // Ensure the current window is active
            Window.Current.Activate();
        }

        /// <summary>
        /// The app_ on unhandled exception.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void App_OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var md = new MessageDialog(string.Format("Unexpected exception: {0}", e.Exception.GetBaseException().Message), "Error");

            md.Commands.Add(new UICommand("OK"));
            md.Commands.Add(new UICommand("Report", async command => await ReportException(e.Exception)));
            
            md.ShowAsync().GetResults();
            e.Handled = true;
        }

        /// <summary>
        /// Reports an unhandled exception
        /// </summary>
        /// <param name="ex">The exception to report</param>
        /// <returns>Void task.</returns>
        private static async Task ReportException(Exception ex)
        {
            var version = Package.Current.Id.Version;
            var versionString = string.Format(
                "{0}.{1}.{2}.{3}",
                version.Major,
                version.Minor,
                version.Build,
                version.Revision);

            ex = ex.GetBaseException();
            var body =
                string.Format(
                    "WinKee Exception Report\nException type: {0}\nException message: {1}\nException stack trace: {2}\nAdditional details:\nApplication version: {3}",
                    ex.GetType().Name,
                    ex.Message,
                    ex.StackTrace,
                    versionString);

            var objEmail = new EmailMessage
            {
                Subject = "WinKee Error Report",
                Body = body
            };

            objEmail.To.Add(new EmailRecipient("mar3ek@gmail.com"));

            await EmailManager.ShowComposeNewEmailAsync(objEmail);
        }

        /// <summary>
        /// The create root frame.
        /// </summary>
        private void CreateRootFrame()
        {
            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (RootFrame != null)
            {
                return;
            }

            // Create a Frame to act as the navigation context and navigate to the first page
            RootFrame = new Frame();

            // Associate the frame with a SuspensionManager key                                
            SuspensionManager.RegisterFrame(RootFrame, "AppFrame");

            // Set the default language
            RootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];

            // Place the frame in the current Window
            Window.Current.Content = RootFrame;
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">
        /// The source of the suspend request.
        /// </param>
        /// <param name="e">
        /// Details about the suspend request.
        /// </param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            Debug.WriteLine("OnSuspending");

            var deferral = e.SuspendingOperation.GetDeferral();
            await SuspensionManager.SaveAsync();
            this.ContinuationManager.MarkAsStale();
            deferral.Complete();
        }

        /// <summary>
        /// Handles the Resuming event.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The event arguments.
        /// </param>
        private async void OnResuming(object sender, object e)
        {
            if (RootFrame.CurrentSourcePageType == typeof(DatabasePage))
            {
                // this is necessary, since DatabasePage.OnNavigatedFrom removes the handler
                // OnNavigatedFrom is invoked on suspension, resulting in no handler attached on resume
                var page = RootFrame.Content as DatabasePage;

                if (page != null)
                {
                    HardwareButtons.BackPressed -= page.HardwareButtonsOnBackPressed;
                    HardwareButtons.BackPressed += page.HardwareButtonsOnBackPressed;
                }
            }

            // this delay is resolves the race condition caused by this method being async
            // while waiting, OnFileActivated might get calledm which will acquire the semaphre
            // that will result in the two operations being called in order OnFileActivated, OnResuming
            // the reverse behaviour causes GUI problems when the master password is set
            await Task.Delay(250);

            Semaphore.WaitOne();

            try
            {
                if (RootFrame.CurrentSourcePageType == typeof(MainPage))
                {
                    return;
                }

                var pinSetting = ApplicationData.Current.LocalSettings.Values[Definitions.PinSettingKey];
                if (pinSetting == null || (bool)pinSetting != true)
                {
                    return;
                }

                var dialog = new PINDialog();

                var result = await dialog.ShowAsync();

                if (result != ContentDialogResult.Primary)
                {
                    this.Exit();
                }
            }
            finally
            {
                Semaphore.Release();
            }
        }

        #endregion
    }
}